/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import BUS.DatabaseBUS;
import DTO.DataTableDTO;
import DTO.DataType;
import DTO.DatabaseDTO;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

/**
 *
 * @author TrongKhoa
 */
public class frmMain extends JFrame implements ActionListener, TreeSelectionListener
{

    public static final Locale[] SupportedLanguage =
    {
        Locale.ENGLISH,
        new Locale("vi", "VI")
    };

    public frmMain() throws Exception
    {
        super("SQL Server_0912_212_224_346");
        _currentLocale = SupportedLanguage[1];
        InitComponents();
        _databaseBusService = new DatabaseBUS();
        _databaseBusService.SetServerPath("D:/Khoa/");
        DialogConnectToServer dlg = new DialogConnectToServer(this);
        dlg.setVisible(true);
    }
    //fields declaration
    private Locale _currentLocale;
    Container _contentPane;
    JLabel _lblStatus;
    JTree _mainTree;
    JTabbedPane _mainTabPanel;
    DatabaseBUS _databaseBusService;
    private ArrayList<DatabaseDTO> _databases = new ArrayList<>();
    DefaultMutableTreeNode _treeRoot;
    protected DefaultTreeModel _treeModel;
    private JPopupMenu _popupTreeLevel1;
    private JPopupMenu _popupTreeLevel2;
    private JPopupMenu _popupTreeLevel3;
    private JPopupMenu _popupTreeLevel4;
    private JPopupMenu _popupTreeLevel5;
    private JPopupMenu _popupTreeLevel6;
    protected JTable _table;
    protected DefaultTableModel _tableModel;
    protected String _serverPath;
    protected String _userName;
    protected String _passWord;
    private MouseListener _treeMouseListener = new MouseAdapter()
    {

        @Override
        public void mouseReleased(MouseEvent e)
        {
            if (e.isPopupTrigger())
            {
                TreePath path = _mainTree.getPathForLocation(e.getX(), e.getY());
                if (path == null)
                {
                    return;
                }

                _mainTree.setSelectionPath(path);

                DefaultMutableTreeNode cpn = (DefaultMutableTreeNode) _mainTree.getLastSelectedPathComponent();

                Helper.Print(cpn.getDepth());
                //Tùy theo level mà tính, lấy ra component gì
                //2 => table
                //1 => database
                //0 => root
                switch (cpn.getLevel())
                {
                    case 0:
                        _popupTreeLevel1.show(e.getComponent(), e.getX(), e.getY());
                        break;
                    case 1:
                        _popupTreeLevel2.show(e.getComponent(), e.getX(), e.getY());
                        break;
                    case 2:
                        _popupTreeLevel3.show(e.getComponent(), e.getX(), e.getY());
                        break;
                    default:
                        break;
                }
            }
        }
    };

    /*
     * private java.util.List<DatabaseDTO> listDataDTO = new
     * ArrayList<DatabaseDTO>(); // private List<DefaultTableModel> listModel =
     * new ArrayList<DefaultTableModel>(); private java.util.List<TempData>
     * listTempData = new ArrayList<TempData>(); private java.util.List<JTable>
     * listJTable = new ArrayList<JTable>(); protected static final String[]
     * validStates = { "", "int", "nvarchar", "varchar", "string" }; int i = 0;
     */
    private void InitComponents() throws Exception
    {
        LoadResource();
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        _contentPane = new Container();
        this.setContentPane(_contentPane);
        //_contentPane = this.getContentPane();
        _contentPane.setLayout(new BorderLayout());
        _contentPane.setPreferredSize(new Dimension(450, 130));
        InitMenuBar();
        InitToolBar();
        InitCenterContent();
        InitFooter();

        try
        {
            ImageIcon icon = new ImageIcon(this.getClass().getResource("/GUI/Res/icon24x24.png"));
            this.setIconImage(icon.getImage());
        }
        catch (Exception e)
        {
            Helper.Print("Đường dẫn Icon không đúng!");
        }
        //this.setBackground(Color.yellow);

        setResizable(true);
        setSize(900, 500);
        setVisible(true);
        //center jframe
        this.setLocationRelativeTo(null);

        //Dialog connect to server
//        dialogConnectServer = new DialogConnectToServer(this, frame);
//        dialogConnectServer.showPlease();
    }

    private void InitMenuBar()
    {
        JMenuBar menuBar = new JMenuBar();
        menuBar.setBorder(new BevelBorder(BevelBorder.RAISED));

        JMenuItem menuItem;

        //Menu File
        JMenu menuFile = new JMenu(_fileStr);
        menuFile.setMnemonic(KeyEvent.VK_F);

        menuItem = new JMenuItem(_connectStr);
        menuFile.add(menuItem);

        menuItem = new JMenuItem(_disconnectStr);
        menuFile.add(menuItem);
        menuFile.addSeparator();
        JMenu menuFileNew = new JMenu(_newStr);
        menuFileNew.setMnemonic(KeyEvent.VK_N);
        menuItem = new JMenuItem(_databaseStr);
        menuFileNew.add(menuItem);
        menuItem = new JMenuItem(_sqlQueryStr);
        menuFileNew.add(menuItem);
        menuFile.add(menuFileNew);
        menuItem = new JMenuItem(_openStr);
        menuFile.add(menuItem);
        menuItem = new JMenuItem(_exitStr);
        menuFile.add(menuItem);

        menuBar.add(menuFile);

        //Menu Language
        JMenu menuLanguage = new JMenu(_languageStr);
        menuBar.add(menuLanguage);
        menuItem = new JMenuItem("English");
        menuLanguage.add(menuItem);
        menuItem.addActionListener(this);
        menuItem.setActionCommand("LanguageEnglish");
        menuItem = new JMenuItem("Tiếng Việt");
        menuItem.addActionListener(this);
        menuItem.setActionCommand("LanguageVietnamese");
        menuLanguage.add(menuItem);


        //Menu Help
        JMenu menuHelp = new JMenu(_helpStr);
        menuHelp.setMnemonic(KeyEvent.VK_H);
        menuItem = new JMenuItem(_aboutStr);
        menuHelp.add(menuItem);

        menuBar.add(menuHelp);

        this.setJMenuBar(menuBar);
    }
    //String resource
    String _fileStr;
    String _connectStr;
    String _disconnectStr;
    String _newStr;
    String _databaseStr;
    String _sqlQueryStr;
    String _openStr;
    String _exitStr;
    String _languageStr;
    String _helpStr;
    String _aboutStr;
    String _toolBarStr;
    String _newQueryStr;
    String _refreshStr;
    String _executeStr;
    String _newDatabaseStr;
    String _attachStr;
    String _deleteStr;
    String _newTableStr;
    String _editStr;
    String _insertStr;
    String _renameStr;
    String _designStr;

    private void LoadResource()
    {
        _fileStr = MultilanguageHelper.GetResource(_currentLocale, "file");
        _connectStr = MultilanguageHelper.GetResource(_currentLocale, "connect");
        _disconnectStr = MultilanguageHelper.GetResource(_currentLocale, "disconnect");
        _newStr = MultilanguageHelper.GetResource(_currentLocale, "new");
        _databaseStr = MultilanguageHelper.GetResource(_currentLocale, "database");
        _sqlQueryStr = MultilanguageHelper.GetResource(_currentLocale, "sqlquery");
        _openStr = MultilanguageHelper.GetResource(_currentLocale, "open");
        _exitStr = MultilanguageHelper.GetResource(_currentLocale, "exit");
        _languageStr = MultilanguageHelper.GetResource(_currentLocale, "language");
        _helpStr = MultilanguageHelper.GetResource(_currentLocale, "help");
        _aboutStr = MultilanguageHelper.GetResource(_currentLocale, "about");
        _toolBarStr = MultilanguageHelper.GetResource(_currentLocale, "toolbar");
        _newQueryStr = MultilanguageHelper.GetResource(_currentLocale, "newquery");
        _refreshStr = MultilanguageHelper.GetResource(_currentLocale, "refresh");
        _executeStr = MultilanguageHelper.GetResource(_currentLocale, "execute");
        _newDatabaseStr = MultilanguageHelper.GetResource(_currentLocale, "newdatabase");
        _attachStr = MultilanguageHelper.GetResource(_currentLocale, "attachdatabase");
        _deleteStr = MultilanguageHelper.GetResource(_currentLocale, "delete");
        _newTableStr = MultilanguageHelper.GetResource(_currentLocale, "newtable");
        _editStr = MultilanguageHelper.GetResource(_currentLocale, "edit");
        _insertStr = MultilanguageHelper.GetResource(_currentLocale, "insert");
        _renameStr = MultilanguageHelper.GetResource(_currentLocale, "rename");
        _designStr = MultilanguageHelper.GetResource(_currentLocale, "design");
    }

    private void InitToolBar()
    {
        JToolBar toolBar = new JToolBar(_toolBarStr);

        JButton button = makeNavigationButton(_newQueryStr, "NewQuery");
        toolBar.add(button);

        button = makeNavigationButton(_refreshStr, "Refresh");
        toolBar.add(button);

        button = makeNavigationButton(_executeStr, "ExcuteQuery");
        toolBar.add(button);

        _contentPane.add(toolBar, BorderLayout.PAGE_START);
    }

    private JButton makeNavigationButton(String altText, String actionCommand)
    {
        JButton button = new JButton(altText);
        button.setPreferredSize(new Dimension(110, 26));
        button.setActionCommand(actionCommand);
        button.addActionListener(this);
        return button;
    }

    private void InitCenterContent() throws Exception
    {
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setOpaque(true);
        mainPanel.setBorder(new BevelBorder(BevelBorder.RAISED));
        JPanel leftContent = InitLeftContent();
        JPanel rightContent = InitRightContent();
        JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftContent, rightContent);
        _contentPane.add(sp, BorderLayout.CENTER);
    }

    private JPanel InitLeftContent() throws Exception
    {
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setOpaque(true);
        mainPanel.setPreferredSize(new Dimension(150, 50));
        mainPanel.setMinimumSize(new Dimension(120, 50));

        _treeRoot = new DefaultMutableTreeNode(_databaseStr);
        _mainTree = new JTree(_treeRoot);
        _popupTreeLevel1 = CreatePopupMenu(new String[]
                {
                    _newDatabaseStr, _attachStr, _refreshStr
                }, new String[]
                {
                    "NewDatabase", "AttachDatabase", "Refresh"
                });
        _popupTreeLevel2 = CreatePopupMenu(new String[]
                {
                    _newTableStr, _newQueryStr, _renameStr, _deleteStr, _refreshStr
                }, new String[]
                {
                    "NewTable", "NewQuery", "RenameDatabase", "DeleteDatabase", "Refresh"
                });
        _popupTreeLevel3 = CreatePopupMenu(new String[]
                {
                    _designStr, _editStr, _renameStr, _deleteStr, _refreshStr
                }, new String[]
                {
                    "DesignTable", "EditTable", "RenameTable", "DeleteTable", "Refresh"
                });

        _mainTree.setShowsRootHandles(true);
        _mainTree.setVisible(true);
        _mainTree.addTreeSelectionListener(this);
        _mainTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        _mainTree.addMouseListener(_treeMouseListener);
        JScrollPane s = new JScrollPane();
        s.getViewport().add(_mainTree);
        mainPanel.add(s);
        return mainPanel;
    }

    private JPanel InitRightContent() throws Exception
    {
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setOpaque(true);
        mainPanel.setMinimumSize(new Dimension(450, 50));
        _mainTabPanel = new JTabbedPane();
        _mainTabPanel.setComponentPopupMenu(_popupTreeLevel6);
        _mainTabPanel.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);

        mainPanel.add(_mainTabPanel);
        return mainPanel;
    }
    JPanel panel1;

    // Nếu chưa có tab này, thì thêm vào và focus tab đó
    // Nếu đã có, thì chỉ focus mà ko thêm
    // Trả về panel của tab được thêm vào
    public JPanel AddTab(String name, JPanel panel)
    {

        ArrayList<String> tabsname = new ArrayList();
        for (int i = 0; i < _mainTabPanel.getTabCount(); i++)
        {
            tabsname.add(_mainTabPanel.getTitleAt(i));
        }

        int index = tabsname.indexOf(name);

        if (index < 0)
        {
            _mainTabPanel.addTab(name, panel);
            index = _mainTabPanel.indexOfComponent(panel);
            _mainTabPanel.setTabComponentAt(index, new ButtonTabComponent(_mainTabPanel));
        }
        _mainTabPanel.setSelectedIndex(index);
        return (JPanel) _mainTabPanel.getComponentAt(index);
    }

    private JPopupMenu CreatePopupMenu(String[] texts, String[] actionCommands) throws Exception
    {
        if (texts.length < 1 || texts.length != actionCommands.length)
        {
            throw new Exception("Độ dài mảng text phải >= 1 và 2 mảng phải có độ dài bằng nhau");
        }

        JPopupMenu popup = new JPopupMenu();
        for (int i = 0; i < texts.length; i++)
        {
            JMenuItem menuItem = new JMenuItem(texts[i]);
            menuItem.setActionCommand(actionCommands[i]);
            menuItem.addActionListener(this);
            popup.add(menuItem);
        }

        return popup;
    }

    private void InitFooter()
    {
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setOpaque(true);
        mainPanel.setPreferredSize(new Dimension(900, 30));
        _lblStatus = new JLabel("Status");

        mainPanel.add(_lblStatus);
        _contentPane.add(mainPanel, BorderLayout.PAGE_END);
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        String actionCommand = e.getActionCommand();
        switch (actionCommand)
        {
            case "LanguageEnglish":
                _currentLocale = SupportedLanguage[0];
                try
                {
                    this.InitComponents();
                }
                catch (Exception ex)
                {
                    Logger.getLogger(frmMain.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;
            case "LanguageVietnamese":
                _currentLocale = SupportedLanguage[1];
                try
                {
                    this.InitComponents();
                }
                catch (Exception ex)
                {
                    Logger.getLogger(frmMain.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;
            case "Refresh":
                RefreshTree();
                break;
            case "NewDatabase":
                //String result = JOptionPane.showInputDialog(this, "Database Name", "Database01");
                //DatabaseDTO newDB = _databaseBusService.CreateNewDatabase(result);
                DatabaseDTO newDB = _databaseBusService.LoadExistingDatabase("D:/data.xml");
                _databases.add(newDB);
                RefreshTree();
                break;
            case "DesignTable":
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) _mainTree.getLastSelectedPathComponent();
                DataTableDTO selectedTable = (DataTableDTO) selectedNode.getUserObject();
                MyEditTablePanel panel = new MyEditTablePanel(this);
                panel.SetTableModel(new TableDesignModeValues(selectedTable, selectedTable.getColumns()));

                AddTab(selectedTable.getTableName() + " Edit", panel);

                break;
            default:
                break;
        }
    }

    private void RefreshTree()
    {
        _treeRoot.removeAllChildren();
        for (DatabaseDTO db : _databases)
        {
            DefaultMutableTreeNode dbNode = new DefaultMutableTreeNode(db);
            _treeRoot.add(dbNode);
            for (DataTableDTO table : db.getTables())
            {
                dbNode.add(new DefaultMutableTreeNode(table));
            }
        }

        ((DefaultTreeModel) _mainTree.getModel()).reload();
    }

    //Xử lý click trên Trees
    @Override
    public void valueChanged(TreeSelectionEvent e)
    {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) _mainTree.getLastSelectedPathComponent();
        if (node == null)
        {
            return;
        }
    }

    //Getters And Setters
    public Locale getCurrentLocale()
    {
        return _currentLocale;
    }
}
